/**
 * @name axiosIns
 * @desc axios二次封装,主要设置拦截器
 */

const baseUrl = 'https://api.mywebsite.com'

function request(method, url, params, options) {
  const isGet = method === 'GET'
  let query = ''
  if (isGet && params) {
    query += '?'
    for (const key in params) {
      if (params.hasOwnProperty(key)) {
        query += `${key}=${params[key]}&`
      }
    }
    query = query.slice(0, -1)
  }
  const urlStr = `${baseUrl}/${url}${query}`

  return (resolve, reject) => {
    wx.request({
      url: urlStr,
      data: isGet ? null : params,
      method,
      header: { token: 'the-token' },
      success: res => resolve(res),
      fail: err => reject(err)
    })
  }
}

function get(url, params, options) {
  return new Promise(request('GET', url, params, options))
}

function post(url, params, options) {
  return new Promise(request('POST', url, params, options))
}

export { get, post }
